package cz.proks.easyhelpdesk.gae.api.impl.db;

import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import cz.proks.easyhelpdesk.api.OAuth2TokenApi;
import cz.proks.easyhelpdesk.api.config.Configuration;
import cz.proks.easyhelpdesk.api.exception.ApiException;
import cz.proks.easyhelpdesk.api.model.OAuth2Token;

@Repository(Configuration.DB.OAUTH2_TOKEN_API)
@Scope("prototype")
public class OAuth2TokenApiImpl extends BaseApiImpl<OAuth2Token> implements OAuth2TokenApi {
    private final Logger log = LoggerFactory.getLogger(getClass());
           
    @Override
    protected Class<OAuth2Token> getDomainClass() {
        return OAuth2Token.class;
    }    
    
    @Override
    protected OAuth2Token getDboObject(OAuth2Token entity) {
        cz.proks.easyhelpdesk.gae.api.impl.dbo.OAuth2Token dbo = instantiateDbo(entity);

        if (dbo != null)
            dbo.toDbo(entity);

        return dbo;
    }

    @Override
    @Transactional(readOnly = false)
    public void deleteAllForProviderId(String providerId) throws ApiException{
        log.debug("deleteAllForProviderId():: Start with providerId '{}'", providerId);
        
        if (StringUtils.hasText(providerId)) {
            Query query = getEntityManager().createNamedQuery("OAuth2Token.deleteAllForProviderId");
            query.setParameter("providerId", providerId);
            int deleted = query.executeUpdate();
            log.debug("deleteAllForProviderId():: Exit with {} row(s) deleted", deleted);
        } else 
            log.debug("deleteAllForProviderId():: Skipped");        
    }     

}
